/**
 * All rights Reserved, Designed By OprCalf
 * Copyright:    Copyright(C) 2016-2020
 * Company       LengYin Ltd.
 */
package com.platform.gateway.common.filter;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import com.platform.gateway.common.utils.MsgUtils;

/**
 * @projectName:  platform-gateway-demo
 * @package:      com.platform.gateway.common.filters
 * @className:    FallbackFilter.java
 * @description:  路由断路器
 * @author:       OprCalf
 * @date:         2020年3月4日
 */
@Component
public class FallbackFilter implements FallbackProvider {

    @Override
    public String getRoute() {
        // 表明为哪个微服务提供回退，return "*"代表为所有微服务提供回退
        return "*";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                // 获取状态码(200,OK)
                return HttpStatus.BAD_GATEWAY;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                // 返回数字状态码
                return HttpStatus.BAD_GATEWAY.value();
            }

            @Override
            public String getStatusText() throws IOException {
                // 返回字母状态码
                return "OK";
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                // 返回的内容
                return new ByteArrayInputStream(MsgUtils.buildFailureMsg("找不到服务,请稍后再试").toString().getBytes("utf-8"));
            }

            @SuppressWarnings("deprecation")
            @Override
            public HttpHeaders getHeaders() {
                final HttpHeaders headers = new HttpHeaders();
                // 返回时的Header体的设置
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                return headers;
            }
        };
    }

}
